package JavaSE.d6;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/*
通过2种方法得到Class类实例
取得SchoolGirl类的所有构造器信息
取得SchoolGirl类的所有字段信息
取得SchoolGirl类的所有方法信息
通过方法Method类，调用test方法
通过方法Method类，调用setName方法
 */
class SchoolGirl {
    private  String name;
    transient String city;
    protected String school;
    public static int age;

    public SchoolGirl() {

    }

    public SchoolGirl(String name) {

    }
    public SchoolGirl(String name,int x) {
        this.name=name;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "SchoolGirl [name=" + name + ", city=" + city + ", school=" + school + ", age=" + age + "]";
    }

    public void test() {
        System.out.println("test");
    }
}
public class Test13 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class c1 = Class.forName("JavaSE.d6.SchoolGirl");//通过forname获得Class类
        Class c2 = SchoolGirl.class;//通过.class获得Class类
        //取得SchoolGirl类的所有构造器信息
        System.out.println("SchoolGirl类的所有构造器信息,权限public");
        Constructor[] constructors = c1.getConstructors();//public
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        System.out.println("SchoolGirl类的所有构造器信息");
        Constructor[] declaredConstructors = c1.getDeclaredConstructors();//全部的
        for (Constructor declaredConstructor : declaredConstructors) {
            System.out.println(declaredConstructor);
        }
        //取得SchoolGirl类的所有字段信息
        System.out.println("取得SchoolGirl类的所有字段信息");
        for (Field declaredField : c1.getDeclaredFields()) {
            System.out.println(declaredField);
        }
        //取得SchoolGirl类的所有方法信息
        System.out.println("取得SchoolGirl类的所有方法信息");
        Method[] declaredMethods = c1.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            System.out.println(declaredMethod);
        }
        System.out.println("调用指定方法test");
        //通过反射创建类对象
        SchoolGirl schoolGirl = (SchoolGirl) c1.newInstance();
        //调用指定方法test
        Method test = c1.getMethod("test", null);
        test.invoke(schoolGirl,null);
        System.out.println("调用指定方法setName");
        //调用指定方法setName
        Method setName = c1.getMethod("setName", String.class);
        setName.invoke(schoolGirl, "你好,我叫");
        System.out.println(schoolGirl.getName());
    }
}
